package com.mlk.good.service.impl;

import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.mlk.constant.EngConstant;
import com.mlk.core.component.LayEditAdapt;
import com.mlk.core.component.page.Page;
import com.mlk.core.component.page.Pager;
import com.mlk.core.constants.Constant;
import com.mlk.core.exception.GlobalException;
import com.mlk.core.util.*;
import com.mlk.core.util.validate.ValidateUtils;
import com.mlk.engSystem.constant.SystemParam;
import com.mlk.engSystem.service.EngSysParamService;
import com.mlk.engUser.mapper.EngUserMapper;
import com.mlk.engUser.po.EngUser;
import com.mlk.good.mapper.EngGoodInfoMapper;
import com.mlk.good.mapper.EngGoodIntroduceMapper;
import com.mlk.good.mapper.EngGoodMapper;
import com.mlk.good.mapper.EngGoodPicMapper;
import com.mlk.good.po.EngGood;
import com.mlk.good.po.EngGoodInfo;
import com.mlk.good.po.EngGoodIntroduce;
import com.mlk.good.po.EngGoodPic;
import com.mlk.good.service.EngGoodService;
import com.mlk.good.vo.EngGoodVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商品服务
 * @author xulu
 */
@Service
public class EngGoodServiceImpl implements EngGoodService {

    @Resource
    private EngGoodMapper engGoodMapper;

    @Resource
    private EngGoodInfoMapper engGoodInfoMapper;

    @Resource
    private EngGoodIntroduceMapper engGoodIntroduceMapper;

    @Resource
    private EngGoodPicMapper engGoodPicMapper;

    @Resource
    private EngUserMapper engUserMapper;

    @Resource
    private EngSysParamService engSysParamService;

    @Value("${file.viewPath}")
    private String picPath ;

    /**
     * 分页展示
     * @param good
     * @return
     */
    @Page
    @Override
    public Pager list(EngGood good) {
        List<EngGoodVO> engGoods = this.engGoodMapper.pageList(good);
        DictUtils.DictAdapter adapt = DictUtils.DictAdapter.adapt(EngConstant.GOOD_TYPE);
        engGoods.stream().forEach(e->{
            e.setTypeName(adapt.get(e.getTypeId().toString()));
        });
        return Pager.adapt(engGoods);
    }

    /**
     * 商品新增
     * @param goodVO
     * @return
     */
    @Override
    @Transactional
    public ServerResponse add(EngGoodVO goodVO) {
        ValidateUtils.validate(goodVO);
        // 新增主体信息
        EngGood good = EngGood.builder().build();
        BeanUtils.copyProperties(goodVO,good);
        good.setCreateName(SessionUtils.getUser().getSysUser().getName());
        good.setCreateTime(new Date());
        int count = this.engGoodMapper.insert(good);
        if(count == 0 ){
            return ServerResponse.fail("新增失败");
        }

        // 添加子类信息
        if(!CollectionUtils.isEmpty(goodVO.getItems())){
            goodVO.getItems().stream().forEach(e->{
                ValidateUtils.validate(e);
                if(e.getMinRate().doubleValue() > e.getMaxRate().doubleValue()){
                    throw new GlobalException("积分最小占比不能超过最大占比");
                }
                if(e.getMaxRate().doubleValue() >1){
                    throw new GlobalException("占比不能超过1");
                }
                this.engGoodInfoMapper.insert(e);
            });
        }

        // 增加介绍信息
        EngGoodIntroduce introduce = new EngGoodIntroduce();
        introduce.setGoodId(goodVO.getId());
        introduce.setIntroduceStr(goodVO.getGoodIntroduce());
        this.engGoodIntroduceMapper.insert(introduce);
        return ServerResponse.ok("新增成功");
    }

    @Override
    public LayEditAdapt uploadIntroducePic(MultipartFile file) {
        FileUploadUtils.UploadContext context = FileUploadUtils.uploadContext(file, EngConstant.PicPath.GOOD_INTRODUCE, UUIDUtils.uuid());
        LayEditAdapt result = new LayEditAdapt();
        result.setData(LayEditAdapt.InnerLayEditAdapt.builder().src(picPath+context.getSaveFullPath()).build());
        return result;
    }

    @Override
    @Transactional
    public ServerResponse uploadGoodPic(EngGoodPic pic,MultipartFile file) {
        FileUploadUtils.UploadContext context = FileUploadUtils.uploadContext(file, EngConstant.PicPath.GOOD_MAIN, UUIDUtils.uuid());
        pic.setPicUrl(context.getSaveFullPath());
        int count = this.engGoodPicMapper.insert(pic);
        if(count == 0){
            throw new GlobalException("操作失败");
        }
        return ServerResponse.ok("操作成功",pic);
    }

    @Override
    @Transactional
    public ServerResponse delGoodPic(Integer id) {
        return this.engGoodPicMapper.deleteById(id) == 0?
                ServerResponse.fail("操作失败") : ServerResponse.ok("操作成功");
    }

    @Override
    @Transactional
    public ServerResponse goodChangeStatus(String id) {
        // 查询商品
        EngGood good = this.engGoodMapper.selectById(id);
        if(good == null){
            throw new GlobalException("操作失败,该商品不存在");
        }

        int status = good.getStatus().equals(Constant.status_ok) ? Constant.status_fail : Constant.status_ok;
        int count = this.engGoodMapper.updateById(EngGood.builder().id(id).status(status).build());
        if(count == 0){
            throw new GlobalException("操作失败");
        }
        return ServerResponse.ok("操作成功");
    }

    @Override
    @Transactional
    public ServerResponse updateGoodInfo(EngGood good) {
        int count = this.engGoodMapper.updateById(good);
        if(count == 0){
            throw new GlobalException("操作失败");
        }
        return ServerResponse.ok("操作成功");
    }

    @Override
    public ServerResponse getIntroduce(String id) {
        EngGoodIntroduce engGoodIntroduce = this.engGoodIntroduceMapper.selectById(id);
        return ServerResponse.ok("操作成功",engGoodIntroduce.getIntroduceStr());
    }

    @Override
    @Transactional
    public ServerResponse updateIntroduce(EngGoodIntroduce introduce) {
        int count = this.engGoodIntroduceMapper.updateById(introduce);
        if(count == 0){
            throw new GlobalException("操作失败");
        }
        return ServerResponse.ok("操作成功");
    }

    @Override
    public ServerResponse getGoodPic(String id) {
        List<EngGoodPic> list = this.engGoodPicMapper.selectList(new EntityWrapper<>(EngGoodPic.builder().goodId(id).build()));
        return ServerResponse.ok(list);
    }

    @Page
    @Override
    public Pager goodParamList(String goodId) {
        return Pager.adapt(this.engGoodInfoMapper.selectList(new EntityWrapper<>(EngGoodInfo.builder().goodId(goodId).build())));
    }

    @Override
    @Transactional
    public ServerResponse addGoodParamItem(EngGoodInfo info) {
        int count = this.engGoodInfoMapper.insert(info);
        if(count == 0){
            throw new GlobalException("操作失败");
        }
        return ServerResponse.ok("操作成功");
    }

    @Override
    @Transactional
    public ServerResponse updateParamItem(EngGoodInfo info) {
        int count = this.engGoodInfoMapper.updateById(info);
        if (count == 0){
            throw new GlobalException("操作失败");
        }
        return ServerResponse.ok("操作成功");
    }

    @Override
    @Transactional
    public ServerResponse changeParamItem(Integer id) {
        EngGoodInfo info = this.engGoodInfoMapper.selectById(id);
        int status= info.getStatus().equals(Constant.status_ok) ?
                Constant.status_fail : Constant.status_ok;
        EngGoodInfo temp = new EngGoodInfo();
        temp.setId(id);
        temp.setStatus(status);
        int count = this.engGoodInfoMapper.updateById(temp);
        if(count == 0){
            throw new GlobalException("操作失败");
        }
        return ServerResponse.ok("操作成功");
    }


    @Override
    public ServerResponse queryScore(String openId) {
        EngUser user = this.engUserMapper.selectOne(EngUser.builder().openId(openId).build());
        return ServerResponse.ok(user);
    }

    /**
     * 商品列表
     * @return
     */
    @Override
    @Page
    public Pager goodList(EngGoodVO good) {
        return Pager.adapt(this.engGoodMapper.goodList(good));
    }

    @Override
    public ServerResponse getGoodBanner(String goodId) {
        List<EngGoodPic> engGoodPics = this.engGoodPicMapper.selectList(new EntityWrapper<>(EngGoodPic.builder().goodId(goodId).build()));
        return ServerResponse.ok(engGoodPics.stream().map(EngGoodPic::getPicUrl).collect(Collectors.toList()));
    }

    @Override
    public ServerResponse getGoodMainInfo(String goodId) {
        return ServerResponse.ok(this.engGoodMapper.selectById(goodId));
    }

    @Override
    public ServerResponse getGoodIntroduce(String goodId) {
        return ServerResponse.ok(this.engGoodIntroduceMapper.selectOne(EngGoodIntroduce.builder().goodId(goodId).build()));

    }

    @Override
    public ServerResponse getGoodParamList(String goodId) {
        List<EngGoodInfo> list = this.engGoodInfoMapper.selectList(new EntityWrapper<>(EngGoodInfo.builder().goodId(goodId).status(Constant.status_ok).build()));
        return ServerResponse.ok(list);
    }
}
